package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Item;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class RemoveCartItemServlet extends HttpServlet {

    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        String workingItemId = req.getParameter("workingItemId");

        // 检查 cart 是否为 null
        if (cart == null) {
            session.setAttribute("errMsg", "Cart is not available in the session.");
            req.getRequestDispatcher(ERROR_FORM).forward(req, resp);
            return; // 终止进一步的处理
        }

        // 检查 workingItemId 是否为空或无效
        if (workingItemId == null || workingItemId.isEmpty()) {
            session.setAttribute("errMsg", "Invalid or missing workingItemId parameter.");
            req.getRequestDispatcher(ERROR_FORM).forward(req, resp);
            return; // 终止进一步的处理
        }

        Item item = cart.removeItemById(workingItemId);

        if(item == null){
            session.setAttribute("errMsg","Attempted to remove null CartItem from Cart");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        }
        else {
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }
    }
}
